package com.laobiao.file_netty_lib.packet.command.download;

import java.io.UnsupportedEncodingException;
import java.nio.ByteBuffer;

import com.laobiao.file_netty_lib.content.FileContentApplication;
import com.laobiao.file_netty_lib.exception.FileBaseException;
import com.laobiao.file_netty_lib.packet.command.BaseCommandPacket;
import com.laobiao.file_netty_lib.packet.command.CommandCirculationType;
import com.laobiao.file_netty_lib.packet.command.PacketCommandType;
import com.laobiao.file_netty_lib.util.BinaryConvertUtil;

/**
 * 客户端发送的文件下载命令包 c-s
 * 
 * @author 38079
 *
 */
public class ClientFileDownloadCommand extends BaseCommandPacket {

	/**
	 * 要下载服务器的文件存储路径
	 */
	private String remoteFilePath;

	public ClientFileDownloadCommand() {
		super();
		setCommand(PacketCommandType.DOWNLOAD);
		setBusinessGroup(FileContentApplication.getLastBusinessNumber());
	}

	/**
	 * 根据参数构建下载命令包
	 * 
	 * @param remoteFilePath
	 * @param businessGroup
	 */
	public ClientFileDownloadCommand(String remoteFilePath, Integer businessGroup) {
		super();
		setCommand(PacketCommandType.DOWNLOAD);
		if (businessGroup != null) {
			setBusinessGroup(businessGroup);
		} else {
			setBusinessGroup(FileContentApplication.getLastBusinessNumber());
		}
		this.remoteFilePath = remoteFilePath;
	}

	/**
	 * 根据命令包构建文件上传命令
	 * 
	 * @param commandBytes
	 */
	public ClientFileDownloadCommand(byte[] commandBytes) {
		ByteBuffer buf = setBaseCommand(commandBytes);

		/**
		 * 文件名长度
		 */
		byte[] chunk = new byte[4];
		buf.get(chunk);
		int remoteNameSize = BinaryConvertUtil.byteArrayToInt(chunk);// 文件名长度
		/**
		 * 文件名
		 */
		chunk = new byte[remoteNameSize];
		buf.get(chunk);
		try {
			setRemoteFilePath(new String(chunk, "UTF-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			throw new FileBaseException("接收到的命令中文件名编码失败！", FileBaseException.ERR_PARAM_WRONG);
		}
	}

	public String getRemoteFilePath() {
		return remoteFilePath;
	}

	public void setRemoteFilePath(String remoteFilePath) {
		this.remoteFilePath = remoteFilePath;
	}

	/**
	 * 长度1014
	 */
	@Override
	protected byte[] getCommContentBytes() {
		ByteBuffer buf = ByteBuffer.allocate(1014);
		try {
			byte[] filePathBytes = remoteFilePath.getBytes("UTF-8");
			buf.put(BinaryConvertUtil.intToByteArray(filePathBytes.length));// 设置文件名
			buf.put(filePathBytes);// 设置文件名
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			throw new FileBaseException("文件名无法转换编码：" + remoteFilePath, e, FileBaseException.ERR_PARAM_WRONG);
		}
		return buf.array();
	}

	@Override
	public CommandCirculationType circulationType() {
		// TODO Auto-generated method stub
		return CommandCirculationType.BUSINESS;
	}

	@Override
	public String toString() {
		return "ClientFileDownloadCommand [remoteFilePath=" + remoteFilePath + ", getRemoteFilePath()="
				+ getRemoteFilePath() + ", circulationType()=" + circulationType() + "]";
	}

}
